/**
 * tjftp -- A simple FTP server, using the ANSI C
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>

int ftp_list(const char * dir, char result[]) {
	int res_len = 0;
	DIR *dirptr = NULL;
	struct dirent *entry = NULL;
	if ((dirptr = opendir(dir)) == NULL) {
		perror("open dir error.");
		return -1;
	} else {
		while (entry = readdir(dirptr)) {
			char path[255] = { '\0' };
			sprintf(path, "%s/%s", realpath(dir, NULL), entry->d_name);
			char* rpath = realpath(path, NULL);
			struct stat st;
			if (lstat(rpath, &st) == -1) {
				return -1;
			}
			char dir_mark, or, ow, ox, gr, gw, gx, tr, rw, tx;
			dir_mark = or = ow = ox = gr = gw = gx = tr = rw = tx = '-';
			if (S_ISDIR(st.st_mode)) {
				dir_mark = 'd';
			}
			if ((S_IRUSR & st.st_mode) == S_IRUSR) {
				or = 'r';
			}
			if ((S_IWUSR & st.st_mode) == S_IWUSR) {
				ow = 'w';
			}
			if ((S_IXUSR & st.st_mode) == S_IXUSR) {
				ox = 'x';
			}
			if ((S_IRGRP & st.st_mode) == S_IRGRP) {
				gr = 'r';
			}
			if ((S_IWGRP & st.st_mode) == S_IWGRP) {
				gw = 'w';
			}
			if ((S_IXGRP & st.st_mode) == S_IXGRP) {
				gx = 'x';
			}
			if ((S_IROTH & st.st_mode) == S_IROTH) {
				tr = 'r';
			}
			if ((S_IWOTH & st.st_mode) == S_IWOTH) {
				rw = 'w';
			}
			if ((S_IXOTH & st.st_mode) == S_IXOTH) {
				tx = 'x';
			}
			/*
			 drwxrwxr-x    6 1000     1000         4096 Mar 05 00:35 temp\r\n
			 -rwxrwxrwx    1 1000     1000           44 Jan 30 21:32 temp.txt\r\n
			 */
			struct tm * timeinfo = localtime(&st.st_mtime);
			char mtime[80] = { '\0' };
			strftime(mtime, 80, "%b %d %H:%M", timeinfo);
			char line[255] = { '\0' };
			sprintf(line, "%c%c%c%c%c%c%c%c%c%c%5i %-8i %-8i %8i %s %s\r\n", dir_mark, or, ow, ox, gr, gw, gx, tr, rw, tx, st.st_nlink, st.st_uid, st.st_gid, st.st_size, mtime, entry->d_name);
			int i;
			for (i = 0; i < strlen(line); i++) {
				result[res_len++] = line[i];
			}
		}
		closedir(dirptr);
		free(entry);
		result[res_len] = '\0';
	}
	return 0;
}
